package com.ikingtech.platform.service.system.country.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.framework.sdk.context.event.SystemInitEvent;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.core.support.LogHelper;
import com.ikingtech.framework.sdk.country.api.CountryApi;
import com.ikingtech.framework.sdk.country.model.CountryDTO;
import com.ikingtech.framework.sdk.enums.system.country.ContinentEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.platform.service.system.country.entity.CountryDO;
import com.ikingtech.platform.service.system.country.service.CountryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
@ApiController(value = "/system/country", name = "系统管理-世界国家管理", description = "系统管理-世界国家管理")
public class CountryController implements CountryApi {

    private final CountryService service;

    @Override
    public R<List<CountryDTO>> all() {
        return R.ok(Tools.Coll.convertList(this.service.all(), entity -> Tools.Bean.copy(entity, CountryDTO.class)));
    }

    @EventListener(SystemInitEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void systemInitEventListener() {
        if (this.service.count() > 0) {
            LogHelper.info("INITIALIZE", "County info already exist.");
            return;
        }
        LogHelper.info("INITIALIZE", "Create county.");
        String jsonStr = Tools.Resource.read("country.json");
        List<CountryDO> entities = Tools.Json.toBean(jsonStr, new TypeReference<>() {
        });
        if (Tools.Coll.isNotBlank(entities)) {
            this.service.remove(Wrappers.lambdaQuery());
            this.service.saveBatch(Tools.Coll.traverse(entities, entity -> {
                entity.setId(Tools.Id.uuid());
                entity.setContinent(ContinentEnum.ASIA.name());
                return entity;
            }));
        }
    }
}
